<template>
  <audio
    :src="attachImageUrl(songUrl)"
    controls="controls"
    :ref="player"
    preload="true"
    @canplay="canplay"
    @timeupdate="timeupdate"
    @ended="ended"
  >
    <!--（1）属性：controls，preload（2）事件：canplay，timeupdate，ended（3）方法：play()，pause() -->
    <!--controls：向用户显示音频控件（播放/暂停/进度条/音量）-->
    <!--preload：属性规定是否在页面加载后载入音频-->
    <!--canplay：当音频/视频处于加载过程中时，会发生的事件-->
    <!--timeupdate：当目前的播放位置已更改时-->
    <!--ended：当目前的播放列表已结束时-->
  </audio>
</template>

<script lang="ts" setup>
import { ref, watch } from "vue";
import { storeToRefs } from "pinia";
import { HttpManager } from "@/api";
import { useSongStore } from "@/store";

const audioPlayer = ref<HTMLAudioElement>();
const songStore = useSongStore();

const { songUrl, isPlay, volume, changeTime, autoNext } =
  storeToRefs(songStore);

// 播放器引用绑定
const player = (el: HTMLAudioElement) => (audioPlayer.value = el);

// 监听播放状态变化
watch(isPlay, (newVal) => {
  newVal ? audioPlayer.value?.play() : audioPlayer.value?.pause();
});

// 监听播放时间跳转
watch(changeTime, (newTime) => {
  if (audioPlayer.value) audioPlayer.value.currentTime = newTime;
});

// 监听音量变化
watch(volume, (newVolume) => {
  if (audioPlayer.value) audioPlayer.value.volume = newVolume/100.0;
});

function canplay() {
  if (!audioPlayer.value) return;

  // 设置歌曲总时长
  songStore.duration = audioPlayer.value.duration;
  // 自动开始播放
  audioPlayer.value.play();
  songStore.isPlay = true;
}

function timeupdate() {
  if (audioPlayer.value) {
    songStore.curTime = audioPlayer.value.currentTime;
  }
}

function ended() {
  songStore.$patch({
    isPlay: false,
    curTime: 0,
    autoNext: !autoNext.value,
  });
}

const attachImageUrl = HttpManager.attachImageUrl;
</script>
<style scoped>
audio {
  display: none;
}
</style>
